package com.xiaolu.xiaoluaicodebackend.aop;



import com.xiaolu.xiaoluaicodebackend.conntation.AuthCheck;
import com.xiaolu.xiaoluaicodebackend.exception.BusinessException;
import com.xiaolu.xiaoluaicodebackend.exception.ErrorCode;
import com.xiaolu.xiaoluaicodebackend.model.entity.User;
import com.xiaolu.xiaoluaicodebackend.model.enums.UserRoleEnum;
import com.xiaolu.xiaoluaicodebackend.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint 切入点
     * @param authCheck 权限校验注解
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //获取注解上的信息对象
        String mustRole = authCheck.mustRole();

        //通过上下文 获取 HttpServletRequest
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();

        //使用HttpServletRequest 获取当前用户的登录信息
        User loginUser = userService.getLoginUser(request);

        //获取注解对象里边的信息
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);

        //如果里边信息为空，则不需要权限，放行
        if (mustRoleEnum == null){
           return joinPoint.proceed();
        }

        //以下为必须有权限才能通过
        //获取当前用户的权限
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        //没有权限
        if (userRoleEnum == null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //要求   必须有管理员权限这个信息   ，  但是用户没有管理员权限  这样就能抛出没有权限了 （如果这个信息是用户就直接放行，不是就是管理员必须接受检验）
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)&&!UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }

        //放行
        return joinPoint.proceed();

    }
}

